var express = require('express');
var router = express.Router();
var Goods = require('../models/Goods'); // 引入模型
var async = require('async');
/* GET users listing. */
var request = require('request');
var app = express();
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization,Origin,Accept,X-Requested-With');
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('X-Powered-By', ' 3.2.1');
  res.header('Content-Type', 'application/json;charset=utf-8');
  if (req.method === 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
});
router.all('/', function (req, res) {
  res.send({
    title: 'Express',
    content: '欢迎访问商品'
  })
})
router.post('/addgoods', (req, res) => {
  let good_info = req.body;
  console.log(good_info.goods_name);
  let datas = {
    goods_name: '无大河网iu'
  }
  Goods.find({
    goods_name: good_info.goods_name
  }, (err, data) => {
    if (err) return res.send({
      msg: '系统错误'
    });
    console.log(data)
    if (data.length > 0) {
      return res.send({
        msg: '商品已经添加',
        status: 3,
        data: []
      })
    }else{
      Goods.create(good_info, (err, data) => {
        if (err) return false;
        res.send({
          msg: '添加成功',
          status: 4,
          data: data
        })
      })
    }
   
  })
})
router.post('/findGoods',(req,res)=>{
  Goods.find().exec((err,data)=>{
    if(err) res.send({msg:'查询出错'});
    res.send({
      data:data,
      msg:'查询成功',
      status:4
    })
  })
})
router.post('/updateGoods',(req,res)=>{
  Goods.update().where().exec((err,data)=>{
     if(err) return res.send({msg:'更新失败'});
     res.send({
       msg:'更新成功',
       status:4,
       data:data
     })
  })
})
module.exports = router;